import { Dialog } from "antd-mobile";

/**
 * 随机生成某个区间的随机整数
 * @param {number} min 
 * @param {number} max 
 * @returns 
 */
function randoms(min: number, max: number) {
    const random = Math.random() * (max - min) + min;
    return Math.ceil(random);
}

/**
 * 根据时间戳获取时间相关时间字符串形式
 * @param {number} shijianchuo 时间戳
 * @param {string} type 类型 day week
 * @param {string} excursion 日期子类型 1.年 2.年月 3.年月日 4.年月日时 5.年月日时分 6.年月日时分秒
 * @param {number | string} symbol 日期连接符
 * @param {number} num 时间偏移量
 * @returns 
 */
function getTime(shijianchuo: number, type: string, excursion: string, symbol: string | number, num: number) {
    function add0(m: number) {
        return m < 10 ? '0' + m : m
    }
    //时间戳转格式时间及星期
    if (type === 'day') {
        const time = shijianchuo ? new Date(shijianchuo + (24 * 60 * 60 * 1000 * num)) : new Date(new Date().valueOf() + (24 * 60 * 60 * 1000 * num));
        const year = time.getFullYear();
        const month = time.getMonth() + 1;
        const day = time.getDate();
        const hour = time.getHours();
        const minute = time.getMinutes();
        const second = time.getSeconds();
        // const timevalue = time.valueOf();
        if (excursion === '1') {
            return year;
        } else if (excursion === '2') {
            return `${year}${symbol}${add0(month)}`;
        } else if (excursion === '3') {
            return `${year}${symbol}${add0(month)}${symbol}${add0(day)}`;
        } else if (excursion === '4') {
            return `${year}${symbol}${add0(month)}${symbol}${add0(day)} ${add0(hour)}`;
        } else if (excursion === '5') {
            return `${year}${symbol}${add0(month)}${symbol}${add0(day)} ${add0(hour)}:${add0(minute)}`;
        }else if (excursion === '6') {
            return `${year}${symbol}${add0(month)}${symbol}${add0(day)} ${add0(hour)}:${add0(minute)}:${add0(second)}`;
        } 
    } else if (type === 'week') {
        const time = shijianchuo ? new Date(shijianchuo) : new Date();
        if (time.getDay() === 0) return "周日";
        if (time.getDay() === 1) return "周一";
        if (time.getDay() === 2) return "周二";
        if (time.getDay() === 3) return "周三";
        if (time.getDay() === 4) return "周四";
        if (time.getDay() === 5) return "周五";
        if (time.getDay() === 6) return "周六";
    }
}
/**
 * 判断两个日期是否大于n个月
 * @param {string} startDate 开始时间 
 * @param {string} endDate 结束时间
 * @param {number} n 是否大于的月份数
 * @returns 
 */
function isTimeGreaterThanNMonths(startDate: string, endDate: string, n: number) {
    let monthsDiff = 0;
    const start: Date | number = new Date(startDate.replace(/-/g, "/"));
    const end: Date | number = new Date(endDate.replace(/-/g, "/"));
    // 获取两个日期的年份和月份
    const year1 = start.getFullYear();
    const month1 = start.getMonth();
    const day1 = start.getDate();
    const year2 = end.getFullYear();
    const month2 = end.getMonth();
    const day2 = end.getDate();
    // 计算年份差
    const yearDiff = year2 - year1;
    // 计算月份差
    if (yearDiff > 0) {
      monthsDiff = (12 - month1) + (yearDiff - 1) * 12 + month2;
    } else {
      monthsDiff = month2 - month1;
    }
    // 考虑跨年、跨闰年的情况
    let leapYearCount = 0;
    for (let i = year1 + 1; i < year2; i++) {
      if (isLeapYear(i)) {
        leapYearCount++;
      }
    }
    // 判断日期差是否大于n个月
    if (month2 > month1) {
      monthsDiff += leapYearCount;
    } else if (month2 < month1) {
      monthsDiff -= leapYearCount;
    } else if (day2 >= day1) { // 月份相等情况下，如果第二个日期的天数大于等于第一个日期的天数，需要加上闰年天数
      monthsDiff += leapYearCount;
    } else { // 否则减去闰年天数
      monthsDiff -= leapYearCount;
    }
    // 判断月份差是否大于n
    return monthsDiff > n;
}

/**
 * 判断是否闰年
 * @param {number} year 年
 * @returns 
 */
function isLeapYear(year:number) {
    return (year % 4 === 0 && year % 100 !== 0) || (year % 400 === 0);
}

/**
 * 计算两个日期之间的天数
 * @param {string} startDate 
 * @param {string} endDate 
 * @returns 
 */
function getDaysBetweenDates(startDate: string, endDate: string) {
    const oneDay = 24 * 60 * 60 * 1000; // 每一天的毫秒数
    const start: Date | number = new Date(startDate.replace(/-/g, "/"));
    const end: Date | number = new Date(endDate.replace(/-/g, "/"));
    // 转换为 UTC 时间，以避免时区影响
    const utcDate1 = Date.UTC(start.getFullYear(), start.getMonth(), start.getDate());
    const utcDate2 = Date.UTC(end.getFullYear(), end.getMonth(), end.getDate());
    // 计算两个 UTC 时间之间的毫秒数差距
    const timeDiff = Math.abs(utcDate2 - utcDate1);
    // 计算天数差距，并考虑闰年情况
    let daysDiff = Math.floor(timeDiff / oneDay);
    // 判断日期2是否在日期1之前，若是则返回负值
    if (end < start) {
      daysDiff = -daysDiff;
    }
    return daysDiff.toString();
}

/**
     * form表单校验规则
     * @param {Array<any>} arr arr[{}] 数组
     */
function ruls(arr:Array<any>) {
    let msg = "";
    for (let i = 0; i < arr.length; i++) {
        if (arr[i].isShow){
            if (arr[i].required && (!arr[i].value && !arr[i].values)){
                return msg = arr[i].placeholder;
            }
            if (arr[i].value && arr[i].rule && !arr[i].rule.test(arr[i].value)){
                return msg = arr[i].ruleMsg;
            }
        }
    }
    return msg;
}
/**
 * 确认弹窗，提示弹窗（失败是否返回首页）
 * @param {string} msg 提示语
 * @param {boolean} isCancel 是否展示取消按钮
 * @param {boolean} isBack 是否返回首页
 * @param {string} cancelText 取消按钮文案 非必传
 * @param {string} confirmText 确认按钮文案 非必传
 */
function back(msg:string, isCancel:boolean, isBack:boolean, cancelText?: string, confirmText?:string){
    return new Promise((resolve,reject)=>{
        let type = sessionStorage.getItem("env")
        let actions = []
        if (isCancel) {
            actions = [
                [
                    {
                        key: 'cancel',
                        text: cancelText || '取消',
                        bold: false,// 是否加粗
                        style: {color: "#333333"},
                        onClick:()=>{
                            console.log("取消");
                            resolve("cancel");
                        }
                    },
                    {
                        key: 'confirm',
                        text: confirmText || '确认',
                        bold: false,// 是否加粗
                        style: {color: "#CBB486"},
                        onClick:()=>{
                            console.log("知道了");
                            if (isBack) {
                                resolve("confirm");
                                if (type === "wechat") {
                                    wx.miniProgram.switchTab({
                                        url: '/pages/my/index/index'
                                    })
                                } else if (type === "alipay") {
                                    my.switchTab({
                                        url: "/pages/indexRevision/indexRevision"
                                    })
                                } else if (type === "app") {
                                    eshimin.closeWindow({
                                        onResponse: function (res:any) {
                                            // console.log(res)
                                        }
                                    });
                                }
                            } else {
                                resolve("confirm");
                            }
                        }
                    },
                ],
            ]
        } else {
            actions = [
                {
                    key: 'confirm',
                    text: confirmText || '知道了',
                    bold: true,// 是否加粗
                    style: {color: "#CBB486"},
                    onClick:()=>{
                        console.log(msg);
                        if (isBack) {
                            resolve("confirm");
                            if (type === "wechat") {
                                wx.miniProgram.switchTab({
                                    url: '/pages/my/index/index'
                                })
                            } else if (type === "alipay") {
                                my.switchTab({
                                    url: "/pages/indexRevision/indexRevision"
                                })
                            } else if (type === "app") {
                                eshimin.closeWindow({
                                    onResponse: function (res:any) {
                                        // console.log(res)
                                    }
                                });
                            }
                        } else {
                            resolve("confirm");
                        }
                    }
                },
            ]
        }
        Dialog.show({
            title: "温馨提示",
            content: msg,
            closeOnAction: true,
            actions: actions,
        })
    });
}
export { 
    randoms,
    getTime,
    isTimeGreaterThanNMonths,
    isLeapYear,
    getDaysBetweenDates,
    ruls,
    back
};
